/*
 * 文件名：UserAction.java
 * 版权：Copyright by www.wootide.com
 * 描述：
 * 修改人：ozm
 * 修改时间：2013-1-29
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
package com.wootide.ets.sys.user.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.opensymphony.xwork2.ActionContext;
import com.wootide.ets.common.Constants;
import com.wootide.ets.common.ErrorCodes;
import com.wootide.ets.common.Page;
import com.wootide.ets.common.QueryCondition;
import com.wootide.ets.common.QueryResults;
import com.wootide.ets.common.Result;
import com.wootide.ets.common.util.CommonUtil;
import com.wootide.ets.log.syslog.RunLog;
import com.wootide.ets.sys.common.action.BaseAction;
import com.wootide.ets.sys.role.service.RoleInfoService;
import com.wootide.ets.sys.user.pojo.UserInfo;
import com.wootide.ets.sys.user.service.UserInfoService;

/**
 * 
 * 用户控制层实现
 * 〈功能详细描述〉
 * @author develop
 * @version 2013-6-20
 * @see UserInfoAction
 * @since
 */
public class UserInfoAction extends BaseAction implements ServletRequestAware
{
    /**
     * 意义，目的和功能，以及被用到的地方<br>
     */
    private static final long serialVersionUID = 1L;
    
    /**
     * 用户信息
     */
    private UserInfo userInfo;
    
    /**
     * 日志
     */
    private RunLog runLog;
    
    /**
     * 用户信息业务层实例
     */
    private UserInfoService userInfoService;
    
    /**
     * 角色信息业务层实例
     */
    private RoleInfoService roleInfoService;
    
    /**
     * 分页信息
     */
    private Page page;
    
    /**
     * 查询条件
     */
    private QueryCondition queryCondition;
    
    /**
     *  Http请求对象
     */
    private HttpServletRequest request;
    
    /**
     *  用户结果集
     */
    @SuppressWarnings("rawtypes")
    private List results;
    
    /**
     * 返回消息
     */
    private String message;
    
    /**
     *  是否操作成功
     */
    private Integer actResult = Constants.ACTRESULT_DEF;
    
    /**
     *  用户ID
     */
    private Integer innerIndex;
    
    /**
     * 用户ID集合
     */
    private Integer[] innerIndexs;
    
    /**
     * 
     * Description: 用户登录<br>
     * Implement: <br>
     * @return
     * @see
     * @return String 跳转标识
     * @author wuliquan
     */
    public String login()
    {
        try
        {
            // 调用业务层获取一个路由对象
            Result result = userInfoService.viewOneUser(userInfo);
            int resultCode = result.getResultCode();
            
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                userInfo = (UserInfo)result.getResultPojo();
                
                ActionContext.getContext()
                        .getSession()
                        .put(Constants.LOGIN_USER, userInfo);
                return SUCCESS;
            }
            else
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                return LOGIN;
            }
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 用户退出<br>
     * Implement: <br>
     * @return
     * @see
     * @return String 跳转标识
     * @author wuliquan
     */
    public String logout()
    {
        try
        {
            ActionContext.getContext().getSession().clear();
            return SUCCESS;
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 获取用户菜单权限<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author develop
     */
    @SuppressWarnings("rawtypes")
    public String toMenus()
    {
        try
        {
            // 获取安全上下文
            SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
            
            // 获取认证对象
            Authentication auth = securityContextImpl.getAuthentication();
            
            // 获取主体对象
            Object principal =  auth.getPrincipal();
            
            
            //获得当前用户所拥有的权限
//            List<GrantedAuthority> authorities = (List<GrantedAuthority>) securityContextImpl.getAuthentication().getAuthorities();
//            for (GrantedAuthority grantedAuthority : authorities) {
//                System.out.println("Authority" + grantedAuthority.getAuthority());
//            }
            
            String username = "";
            
            String password = "";
            
            if(principal instanceof UserDetails)
            {
                username = ((UserDetails)principal).getUsername();
                password = ((UserDetails)principal).getPassword();
            }
            else 
            {
                username = principal.toString();
                password = principal.toString();
            }
            
            UserInfo user = new UserInfo();
            
            user.setUserName(username);
            user.setPassword(password);
            
            
            // 调用业务层获取一个路由对象
            userInfo = (UserInfo)(userInfoService.viewOneUser(user)).getResultPojo();
            
            request.getSession().setAttribute(Constants.LOGIN_USER, userInfo);
            
            // 获取登录用户角色Id
            Integer roleId = userInfo.getRoleInfo().getRoleId();
            
            Result result = userInfoService.queryMenus(roleId, request);
            
            int resultCode = result.getResultCode();
            
            
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                List menus = result.getResultList();
                request.getSession().setAttribute("menus", menus);
                return SUCCESS;
            }
            return ERROR;
        }
            catch (Exception e)
            {
                runLog.error("Unknow Error!", e, request);
                message = getText(Constants.MESSAGE_PREFIX
                        + ErrorCodes.ERRORCODE_UNKNOW);
                return ERROR;
            }
    }
    
    /**
     * 
     * Description:分页查询
     * Implement: <br>
     * @return
     * @see
     * @return String 条转换标识
     * @author ozm2013-1-29下午1:53:19
     */
    public String doQuery()
    {
        try
        {
            // 如果从菜单进入，即在没有分页信息的情况下，则默认进入首页
            if (null == page)
            {
                page = new Page();
                page.setCurPage(1);
            }
            
            // 调用而业务层进行分页查询
            Result result = userInfoService.queryForPages(page, queryCondition);
            
            int resultCode = result.getResultCode();
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                QueryResults queryResults = (QueryResults)result.getResultPojo();
                // 获取服务代码结果集
                runLog.debug(queryResults);
                results = queryResults.getResults();
                // 获取分页信息
                page = queryResults.getPage();
                
                // 跳转到分页页面
                return SUCCESS;
            }
            else
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                return ERROR;
            }
            
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 预添加
     * Implement: <br>
     * @see
     * @return String 跳转标识
     */
    public String toAdd()
    {
        try
        {
            /**
             * 设置页面字段的默认值 默认值
             */
            userInfo = new UserInfo();
            UserInfo user = (UserInfo)ActionContext.getContext()
                    .getSession()
                    .get(Constants.LOGIN_USER);
            userInfo.setUserId(user.getUserId());
            userInfo.setPassword("123456");
            
            // 调用业务层获取一个路由对象
            Result result = roleInfoService.viewAllRoles();
            int resultCode = result.getResultCode();
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                results = result.getResultList();
                // 获取服务代码结果集
                runLog.debug(results);
                
                return SUCCESS;
            }
            else
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                return ERROR;
            }
            
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
        
    }
    
    /**
     * 
     * Description: 添加用户信息
     * Implement: <br>
     * @see
     * @return String 跳转标识
     */
    public String doAdd()
    {
        try
        {
            runLog.debug("userInfo=" + userInfo);
            
            // 调用业务层进行前转MO路由新增操作
            // 用户的创建时间
            userInfo.setCreateTime(CommonUtil.getCurrentTime());
            userInfo.setUpdateTime(CommonUtil.getCurrentTime());
            
            // 用户的默认启用状态  0:禁用  1：启用
            userInfo.setStatus(1);
            
            // 用户是否是系统用户   0:否  1：是
            userInfo.setIsSys(0);
            
            Result result = userInfoService.addOneUser(userInfo, request);
            
            int resultCode = result.getResultCode();
            message = getText(Constants.MESSAGE_PREFIX + resultCode);
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                actResult = Constants.ACTRESULT_SUC;
                return SUCCESS;
            }
            else
            {
                actResult = Constants.ACTRESULT_FAIL;
                return ERROR;
            }
            
        }
        
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            actResult = Constants.ACTRESULT_FAIL;
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
        
    }
    
    /**
     * 
     * Description: 预修改用户信息
     * Implement: <br>
     * @see
     * @return String 跳转标识
     * @author ozm2013-1-29下午3:47:44
     */
    public String toMod()
    {
        try
        {
            // 调用业务层获取一个路由对象
            Result rolesResult = roleInfoService.viewAllRoles();
            Result result = userInfoService.viewOneUser(innerIndex);
            int resultCode = result.getResultCode();
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                userInfo = (UserInfo)result.getResultPojo();
                results = rolesResult.getResultList();
                return SUCCESS;
            }
            else
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                return ERROR;
            }
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description:修改用户信息
     * Implement: <br>
     * @see
     * @return String 跳转标识
     * @author ozm2013-1-29下午4:07:53
     */
    public String doMod()
    {
        
        try
        {
            // 打印入口信息
            runLog.debug("userInfo=" + userInfo);
            
            // 调用业务层进行路由的修改操作
            Result result = userInfoService.modOneUser(userInfo, request);
            int resultCode = result.getResultCode();
            message = getText(Constants.MESSAGE_PREFIX + resultCode);
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                actResult = Constants.ACTRESULT_SUC;
                return SUCCESS;
            }
            else
            {
                actResult = Constants.ACTRESULT_FAIL;
                return ERROR;
            }
        }
        
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            actResult = Constants.ACTRESULT_FAIL;
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 删除用户
     * Implement: <br>
     * @see
     * @return String 跳转标识
     * @author ozm2013-1-29下午4:10:40
     */
    public String doDel()
    {
        try
        {
            runLog.debug("doDel");
            // 调用业务层进行路由的删除操作
            Result result = userInfoService.delUsers(innerIndexs, request);
            int resultCode = result.getResultCode();
            
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                actResult = Constants.ACTRESULT_SUC;
                return SUCCESS;
            }
            // 如果删除中出现失败
            else
            {
                // 取得删除失败的条数
                int delErrorNum = result.getDelErrorNum();
                // 根据总条数和失败条数得出成功的条数
                int delSuccNum = innerIndexs.length - delErrorNum;
                // 定义国际化消息的参数
                String[] params = new String[] {String.valueOf(delSuccNum),
                        String.valueOf(delErrorNum)};
                message = getText(Constants.MESSAGE_PREFIX + resultCode, params);
                actResult = Constants.ACTRESULT_FAIL;
                return ERROR;
            }
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            actResult = Constants.ACTRESULT_FAIL;
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 查看用户详细信息<br>
     * Implement: <br>
     * @return
     * @see
     * @return String 跳转标识
     * @author develop
     */
    public String toDetail()
    {
        try
        {
            // 调用业务层获取一个路由对象
            Result result = userInfoService.viewOneUser(innerIndex);
            int resultCode = result.getResultCode();
            if (ErrorCodes.ERRORCODE_SUCC == resultCode)
            {
                userInfo = (UserInfo)result.getResultPojo();
                return SUCCESS;
            }
            else
            {
                message = getText(Constants.MESSAGE_PREFIX + resultCode);
                return ERROR;
            }
        }
        catch (Exception e)
        {
            runLog.error("Unknow Error!", e, request);
            message = getText(Constants.MESSAGE_PREFIX
                    + ErrorCodes.ERRORCODE_UNKNOW);
            return ERROR;
        }
    }
    
    /**
     * 
     * Description: 新增Ajax校验
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author ozm2013-1-31下午1:35:47
     */
    public String doCheckWhenAdd()
    {
        Result result = userInfoService.checkContentWhenAdd(userInfo.getUserName());
        int resultCode = result.getResultCode();
        message = CommonUtil.getExistCheckMessage(resultCode,
                getText("VALIDATOR.USER.USERNAME"),
                getText("VALIDATOR.USER.USERNAME.PASS"));
        return SUCCESS;
    }
    
    /**
     * 获取系统HttpServletRequest实例
     */
    public void setServletRequest(HttpServletRequest request)
    {
        
        this.request = request;
    }
    
    public UserInfo getUserInfo()
    {
        return userInfo;
    }
    
    public void setUserInfo(UserInfo userInfo)
    {
        this.userInfo = userInfo;
    }
    
    public RunLog getRunLog()
    {
        return runLog;
    }
    
    public void setRunLog(RunLog runLog)
    {
        this.runLog = runLog;
    }
    
    public void setUserInfoService(UserInfoService userInfoService)
    {
        this.userInfoService = userInfoService;
    }
    
    public Page getPage()
    {
        return page;
    }
    
    public void setPage(Page page)
    {
        this.page = page;
    }
    
    public QueryCondition getQueryCondition()
    {
        return queryCondition;
    }
    
    public void setQueryCondition(QueryCondition queryCondition)
    {
        this.queryCondition = queryCondition;
    }
    
    public HttpServletRequest getRequest()
    {
        return request;
    }
    
    public void setRequest(HttpServletRequest request)
    {
        this.request = request;
    }
    
    @SuppressWarnings("rawtypes")
    public List getResults()
    {
        return results;
    }
    
    @SuppressWarnings("rawtypes")
    public void setResults(List results)
    {
        this.results = results;
    }
    
    public String getMessage()
    {
        return message;
    }
    
    public void setMessage(String message)
    {
        this.message = message;
    }
    
    public Integer getActResult()
    {
        return actResult;
    }
    
    public void setActResult(Integer actResult)
    {
        this.actResult = actResult;
    }
    
    public Integer getInnerIndex()
    {
        return innerIndex;
    }
    
    public void setInnerIndex(Integer innerIndex)
    {
        this.innerIndex = innerIndex;
    }
    
    public Integer[] getInnerIndexs()
    {
        return innerIndexs;
    }
    
    public void setInnerIndexs(Integer[] innerIndexs)
    {
        this.innerIndexs = innerIndexs;
    }
    
    public void setRoleInfoService(RoleInfoService roleInfoService)
    {
        this.roleInfoService = roleInfoService;
    }
    
}
